import { Controller, Get, Post, Param, Query, UseGuards, Req, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { NovelService } from './novel.service';
import { CrawlerService } from '../crawler/crawler.service';

@Controller('novels')
export class NovelController {
  constructor(
    private novelService: NovelService,
    private crawlerService: CrawlerService,
  ) {}

  @Get()
  async findAll(@Query('search') search?: string, @Query('page') page = 1, @Query('limit') limit = 10) {
    return this.novelService.findAll(search, Number(page), Number(limit));
  }

  @Get('popular')
  async getPopular(@Query('limit') limit = 10) {
    return this.novelService.getPopularNovels(Number(limit));
  }

  @Get(':id')
  async findOne(@Param('id') id: number) {
    return this.novelService.findOne(Number(id));
  }

  @Get(':id/chapters')
  async getChapters(
    @Param('id') id: number,
    @Query('page') page = 1,
    @Query('limit') limit = 20,
  ) {
    return this.novelService.getChapters(Number(id), Number(page), Number(limit));
  }

  @Get(':id/chapters/:chapterIndex')
  async getChapter(@Param('id') id: number, @Param('chapterIndex') chapterIndex: number) {
    return this.novelService.getChapter(Number(id), Number(chapterIndex));
  }

  @Get('categories/list')
  async getCategories() {
    return this.novelService.getCategories();
  }

  @Get('category/:categoryName')
  async getNovelsByCategory(
    @Param('categoryName') categoryName: string,
    @Query('page') page = 1,
    @Query('limit') limit = 10,
  ) {
    return this.novelService.getNovelsByCategory(categoryName, Number(page), Number(limit));
  }

  @Post('crawl')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  async crawlNovel(@Req() req, @Body() body: { url: string }) {
    const novel = await this.crawlerService.crawlNovelFromUrl(body.url);
    return {
      success: true,
      message: '小说爬取成功',
      novel,
    };
  }

  @Post(':id/continue-crawl')
  @UseGuards(JwtAuthGuard)
  @HttpCode(HttpStatus.OK)
  async continueCrawl(@Param('id') id: number) {
    await this.crawlerService.continueCrawlChapters(Number(id));
    return {
      success: true,
      message: '继续爬取章节成功',
    };
  }

  @Post('create-test-data')
  @HttpCode(HttpStatus.OK)
  async createTestData() {
    await this.novelService.createTestData();
    return {
      success: true,
      message: '测试数据创建成功',
    };
  }
}